package cloudspace.controlpanel.submitter;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;

import org.webcat.submitter.SubmissionTargetException;
import org.webcat.submitter.Submitter;
import org.webcat.submitter.targets.AssignmentTarget;
import org.webcat.submitter.targets.ImportGroupTarget;
import org.webcat.submitter.targets.RootTarget;
import org.webcat.submitter.targets.SubmissionTarget;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.util.GenericComposer;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Radio;
import org.zkoss.zul.Radiogroup;
import org.zkoss.zul.SimpleListModel;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Tree;
import org.zkoss.zul.Treeitem;
import org.zkoss.zul.Window;

import cloudspace.config.ServletLocationFinder;


public class ConfigureSubmitterController extends GenericComposer
{
    /**
     * 
     */
    private static final long serialVersionUID = 5367073060325241250L;

    RootTarget target;

    SubmissionTarget selectedTarget = null;

    Tree assignmentTree;

    Window self;


    public void doAfterCompose( Component window ) throws IOException
    {

        self = (Window)window;
        assignmentTree = (Tree)window.getFellow( "assignmentTree" );
        Radiogroup enableRadio = (Radiogroup)window.getFellow( "submitterStatus" );
        // FIXME: backend config class
        enableRadio.setSelectedItem( (Radio)enableRadio.getChildren().get( 0 ) );
        File internalTargetFile = new File( ServletLocationFinder.getServletResourcePath( "/configs/submissionTarget.xml" ) );

        Submitter submitter = new Submitter();

        submitter.readSubmissionTargets( internalTargetFile.toURI().toURL() );

        target = submitter.getRoot();
        assignmentTree.setModel( new SubmissionTargetTreeModel( target ) );
        assignmentTree.setTreeitemRenderer( new SubmissionTreeitemRenderer() );
        assignmentTree.addEventListener( "onSelect", new EventListener()
        {

            public void onEvent( Event event ) throws Exception
            {
                onTreeSelect( event );

            }

        } );

    }


    // ----------------------------------------------------------
    private void displayError( String errorMessage )
    {
        try
        {
            Messagebox.show( errorMessage,
                "Error",
                Messagebox.OK,
                Messagebox.ERROR );
        }
        catch ( InterruptedException e )
        {
            ;
        }
    }


    public void onAssignmentAdd( Event event )
    {
        Treeitem selected = assignmentTree.getSelectedItem();
        if ( selected == null )
        {
            displayError( "You must select a group before clicking add" );
            return;
        }
        SubmissionTarget parent = (SubmissionTarget)selected.getValue();
        AssignmentTarget newTarget = new AssignmentTarget( parent );
        newTarget.setName( "Test Assignment" );
    }


    public void onTreeSelect( Event event )
    {
        SubmissionTarget target = (SubmissionTarget)( (Tree)event.getTarget() ).getSelectedItem()
            .getValue();
        try
        {
            buildPanel( target );
        }
        catch ( SubmissionTargetException e )
        {
            displayError( "Could not build the info pannel, the submission target is corrupt" );
        }
    }


    private void buildPanel( SubmissionTarget target )
        throws SubmissionTargetException
    {
        String transport;
        String name;
        name = target.getName();
        Textbox nameBox = (Textbox)self.getFellow( "assignmentName" );
        nameBox.setValue( name );

        Textbox hrefBox = (Textbox)self.getFellow( "hrefBox" );
        transport = target.getTransport();
        Label hrefLabel = (Label)self.getFellow( "hrefLabel" );
        if ( target instanceof ImportGroupTarget )
        {
            hrefLabel.setValue( "Href: " );
            transport = ( (ImportGroupTarget)target ).getHref();
        }
        else
        {
            hrefLabel.setValue( "Transport URL: " );
        }

        if ( transport == null )
        {
            hrefBox.setVisible( false );
            hrefLabel.setVisible( false );
        }
        else
        {
            hrefBox.setVisible( true );
            hrefLabel.setVisible( true );
        }
        hrefBox.setValue( transport );
        Listbox paramBox = (Listbox)self.getFellow( "paramBox" );

        Map<String, String> transportParams = target.getTransportParameters();
        Textbox fileBox = (Textbox)self.getFellow( "fileBox" );
        String fileName = transportParams.get( "$file.file1" );
        if ( fileName != null )
        {
            fileBox.setVisible( true );
            fileBox.setValue( fileName );
        }
        else
        {
            fileBox.setVisible( false );
        }
        if ( !transportParams.isEmpty() )
        {

            paramBox.setItemRenderer( new ListitemRenderer()
            {

                public void render( Listitem item, Object data )
                    throws Exception
                {
                    Entry<String, String> param = (Entry<String, String>)data;
                    String paramName = param.getKey();
                    if ( paramName.startsWith( "$file" ) )
                    {
                        item.detach();
                        return;
                    }
                    String paramValue = param.getValue();
                    Listcell name = new Listcell();
                    Listcell value = new Listcell();
                    name.setLabel( paramName );
                    value.setLabel( paramValue );
                    name.setParent( item );
                    value.setParent( item );
                }

            } );
            paramBox.setModel( new SimpleListModel( new ArrayList( transportParams.entrySet() ) ) );
            paramBox.setVisible( true );
        }
        else
        {
            paramBox.setVisible( false );
        }
    }

}
